-- rollback_voucher.lua
-- KEYS[1]: voucher inventory key (voucher:inventory:{voucherId})
-- KEYS[2]: user claimed vouchers key (user:vouchers:{userId})
-- KEYS[3]: user used vouchers key (user:used:{userId})
-- ARGV[1]: voucher code
-- ARGV[2]: user ID

local voucherInventoryKey = KEYS[1]
local userVouchersKey = KEYS[2]
local userUsedVouchersKey = KEYS[3]
local voucherCode = ARGV[1]
local userId = ARGV[2]

-- Check if user has claimed this voucher
local userHasClaimed = redis.call('SISMEMBER', userVouchersKey, voucherCode)
if userHasClaimed == 0 then
    return -1  -- User has not claimed this voucher
end

-- Check if user has already used this voucher
local userHasUsed = redis.call('SISMEMBER', userUsedVouchersKey, voucherCode)
if userHasUsed == 1 then
    return -2  -- Voucher has already been used, cannot rollback
end

-- Atomically increment inventory and remove user claim
redis.call('INCR', voucherInventoryKey)
redis.call('SREM', userVouchersKey, voucherCode)

-- Get current inventory after rollback
local currentInventory = redis.call('GET', voucherInventoryKey)
return tonumber(currentInventory)  -- Return current inventory after rollback